package csc.nndp.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import csc.nndp.dao.User;
import csc.nndp.dao.UserDB;

/**
 * Servlet implementation class Delete
 */
@WebServlet("/Delete")
public class Delete extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Delete() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String userID = request.getParameter("userId"); 
		User e;
		try {
			e = UserDB.getUserById(Integer.valueOf(userID));
		} catch (NumberFormatException e1) {
			throw new ServletException(e1.getMessage());
		} catch (Exception e1) {
			throw new ServletException(e1.getMessage());
		}
		request.setAttribute("user", e);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("delete.jsp");
		dispatcher.forward(request, response);
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		String action = request.getParameter("action");
		List<String> messages = new ArrayList<String>();
		if(action.equals("delete")){
			
			
			User e = new User(Integer.parseInt(request.getParameter("userId")),
					request.getParameter("userName"),
					
					request.getParameter("pass"),
					request.getParameter("firstName"),
					request.getParameter("lastName"),
					request.getParameter("Phone"),
					request.getParameter("email"),
					request.getParameter("role"));
		
				
		
			
					
			request.setAttribute("user", e);
			try {
				UserDB.delete(e);
				
				//messages.add("Updated successfully.");
				request.setAttribute("messages", messages);
				
				
			RequestDispatcher dispatcher = request.getRequestDispatcher("view-user");
			   dispatcher.forward(request, response);
			} catch (Exception e1) {
				throw new ServletException(e1.getMessage());
			}

			    
			}

		}
	}	